package com.spongebob.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spongebob.pojo.*;
import com.spongebob.service.*;
import com.spongebob.util.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 客服表 前端控制器
 * </p>
 *
 * @author tutu
 * @since 2021-03-16
 */
@Controller
@RequestMapping("/customer-service")
public class CustomerServiceController {

    @Autowired
    private CustomerServiceService customerServiceService;
    @Autowired
    private ViewStatisticsService viewStatisticsService;

    @Autowired
    private SessionService sessionService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private SystemMessageService systemMessageService;
    @Autowired
    private WorkOrderService workOrderService;

    /**登录
     * @param customerService
     * @param model
     * @return
     * @Author:xiao
     */
    @PostMapping("/login")
    public String login(CustomerService customerService, Model model,HttpSession session) {
        String email = customerService.getEmail();
        String password;
        password = Md5Utils.MD5Encode(customerService.getPassword() + "", "UTF-8");
        // 根据用户名和密码创建 Token
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        // 获取 subject 认证主体
        Subject subject = SecurityUtils.getSubject();
        try {
            // 开始认证，这一步会跳到我们自定义的 Realm 中
            /**
             * 访问量控制
             **/
            List<ViewStatistics> viewStatisticsList = viewStatisticsService.list();
            viewStatisticsList.get(3).setVisitorcount(viewStatisticsList.get(3).getVisitorcount()+1);
            viewStatisticsService.updateById(viewStatisticsList.get(3));
            int totalView = 0;
            for (ViewStatistics v : viewStatisticsList) {
                totalView += v.getVisitorcount();
            }
            session.setAttribute("visitsCount", totalView);
            session.setAttribute("viewStatistic", viewStatisticsList);
            QueryWrapper<ViewStatistics>qw1=new QueryWrapper<>();
            subject.login(token);
            System.out.println("token");
            return "redirect:/customer-service/index";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("state", 2);
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }

    }

    /**
     * 注册
     * @param customerService
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(CustomerService customerService, Model model) {

        String email = customerService.getEmail();
        String password;
        password = Md5Utils.MD5Encode(customerService.getPassword() + "", "UTF-8");
        customerService.setPassword(password);
        QueryWrapper<CustomerService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("password", password);
        CustomerService one = customerServiceService.getOne(queryWrapper);
        if (one != null) {

            model.addAttribute("registermsg", "账号已注册");
            return "redirect:/register";
        } else {
            customerService.setServicerole("系统管理员");
            customerService.setHeadimg("assets/media/image/user/women_avatar2.jpg");
            this.customerServiceService.save(customerService);
        }

        return "login";
    }

    /*注销*/
    @RequestMapping("/logout")
    public String over(HttpSession session) {
        CustomerService customerService = new CustomerService();
        CustomerService user = (CustomerService) session.getAttribute("user");
        customerService.setState("离线");
        customerService.setCustomerserviceid(user.getCustomerserviceid());
        customerServiceService.updateById(customerService);
        session.invalidate();
        return "login";
    }

    @RequestMapping("/index")
    public String index(Model model, HttpSession session) {
        CustomerService cs = (CustomerService) session.getAttribute("user");
        session.setAttribute("personalInformation", cs);
        System.out.println(cs);

        /**
         * 访问量控制
         **/
//        List<ViewStatistics> viewStatisticsList = viewStatisticsService.list();
//        viewStatisticsList.get(3).setVisitorcount(viewStatisticsList.get(3).getVisitorcount()+1);
//        viewStatisticsService.updateById(viewStatisticsList.get(3));
//        int totalView = 0;
//        for (ViewStatistics v : viewStatisticsList) {
//            totalView += v.getVisitorcount();
//        }
//        session.setAttribute("visitsCount", totalView);
//        model.addAttribute("visitsCount", totalView);
//        session.setAttribute("viewStatistic", viewStatisticsList);
//        QueryWrapper<ViewStatistics>qw1=new QueryWrapper<>();




        /**
         * notice控制
         **/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Notice> listNotice = noticeService.list();


        long time = new Date().getTime();

        ArrayList<Notice> noticelist1 = new ArrayList<>();

        for (Notice n : listNotice) {
            Date s = n.getCreatetime();
            if (s.getTime() - time > 0)
                noticelist1.add(n);
        }
        if (noticelist1.size() != 0) {
            Notice notice = new Notice();
            long leastNotice = noticelist1.get(0).getCreatetime().getTime() - time;
            for (Notice i : noticelist1
            ) {
                Date s = i.getCreatetime();
                if (s.getTime() - time <= leastNotice)
                    notice = i;
            }
            session.setAttribute("noticeContent", notice.getContent());
            session.setAttribute("noticeTime", notice.getCreatetime());
        } else {
            session.setAttribute("noticeContent", "最近无消息");
            session.setAttribute("noticeTime", "null");
        }



        /**
         * systemMassage控制
         **/

        List<SystemMessage> listSystemMessage = systemMessageService.list();
        long leastMassage = listSystemMessage.get(0).getCreatetime().getTime() - time;

        ArrayList<SystemMessage> arrList = new ArrayList<SystemMessage>();


        for (SystemMessage n : listSystemMessage) {

            Date s = n.getCreatetime();
            if (s.getTime() - time > 0)
                arrList.add(n);
        }
        if (arrList.size() != 0) {          /*判断消息是否为空*/
            SystemMessage systemMessage = new SystemMessage();
            long leastSystemMassage = arrList.get(0).getCreatetime().getTime() - time;
            for (SystemMessage i : arrList
            ) {
                Date s = i.getCreatetime();
                if (s.getTime() - time <= leastSystemMassage)
                    systemMessage = i;
            }
            session.setAttribute("systemContent", systemMessage.getContent());
            session.setAttribute("systemTime", systemMessage.getCreatetime());
        } else {
            session.setAttribute("systemContent", "最近无消息");
            session.setAttribute("systemTime", "null");
        }

        /**
         * 工单条形图控制
         **/
        List<WorkOrder> workOrdersList = workOrderService.list();
        Calendar cal = Calendar.getInstance();
        int[] a1 = new int[12];
        int[] a2 = new int[12];
        int[] a3 = new int[12];
        int[] a4 = new int[12];

        if (workOrdersList == null){
            workOrdersList = new ArrayList<WorkOrder>();
        }else{

            for (WorkOrder w : workOrdersList) {
                Date da = w.getUpdatetime();
                cal.setTime(da);
                if ("未分配".equals(w.getState()))
                    a1[cal.get(Calendar.MONTH)]++;
                else if ("待处理".equals(w.getState()))
                    a2[cal.get(Calendar.MONTH)]++;
                else if (("处理中").equals(w.getState()))
                    a3[cal.get(Calendar.MONTH)]++;
                else
                    a4[cal.get(Calendar.MONTH)]++;


            }
        }
/**
 *在线客服，会话量，好评率，已解决问题数 控制
 **/
        session.setAttribute("WorkOrder1", a1);
        session.setAttribute("WorkOrder2", a2);
        session.setAttribute("WorkOrder3", a3);
        session.setAttribute("WorkOrder4", a4);

        QueryWrapper qw2 = new QueryWrapper();
        qw2.eq("state", "在线");
        List<CustomerService> lists = customerServiceService.list(qw2);
        session.setAttribute("list", lists);

        session.setAttribute("listCount", lists.size());

        List<Session> list1 = sessionService.list();
        Integer sessionTotalNumber = 0;
        Integer customerservicemsgnum = 0;
        Integer goodEvaluation = 0;
        Integer evaluationDetail = 0;
        if (list1!=null){
            for (Session s : list1) {
                if (s.getCustomermsgnum()==null||s.getCustomerservicemsgnum()==null){}
               else {
                    sessionTotalNumber += s.getCustomermsgnum() + s.getCustomerservicemsgnum();
                    customerservicemsgnum += s.getCustomerservicemsgnum();
                }
                if ("好评".equals(s.getEvaluation()))
                    goodEvaluation++;
                if ("解决了问题".equals(s.getEvaluationdetail()))
                    evaluationDetail++;
            }
        }

        session.setAttribute("sessionTotalNumber", sessionTotalNumber);
        session.setAttribute("customerServicemsgnum", customerservicemsgnum);
        session.setAttribute("evaluationDetail", evaluationDetail);
        float f = (float) goodEvaluation / sessionService.count() * 100;
        session.setAttribute("goodEvaluationRate", (int) f);
        model.addAttribute("status", 1);
        return "index";
    }
/**
 *修改用户信息
 */

    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public String updatePassword(CustomerService customerService, HttpSession session) {
        CustomerService personalInformation = (CustomerService) session.getAttribute("personalInformation");
        personalInformation.setPassword(customerService.getPassword());
        personalInformation.setEmail(customerService.getEmail());
        personalInformation.setNickname(customerService.getNickname());
        personalInformation.setRealname(customerService.getRealname());
        personalInformation.setServicegroup(customerService.getServicegroup());
        personalInformation.setServicerole(customerService.getServicerole());
        customerServiceService.updateById(personalInformation);
        return "redirect:/customer-service/index";
    }

}





